import { Outlet, useLocation } from 'react-router-dom'
import './index.scss'
import { MusicPlayer } from '../../components'
import { useEffect, useRef } from 'react'

const Portal = ()=>{
    const position = useLocation()

    const musicPlayerRef = useRef<HTMLDivElement>(null)
    const playerHideTimer = useRef<NodeJS.Timeout | null>(null)

    function showMusicPlayer(){
        if(position.pathname === '/music') return
        if(!musicPlayerRef.current) return
        musicPlayerRef.current.style.top = '0'
    }

    function hideMusicPlayer(){
        if(position.pathname === '/music') return
        playerHideTimer.current = setTimeout(()=>{
            if(!musicPlayerRef.current) return
            const rect = musicPlayerRef.current.getBoundingClientRect()
            musicPlayerRef.current.style.top = `-${rect.height}px`
        }, 500)
    }

    function stopHidePlayer(){
        if(playerHideTimer.current) clearTimeout(playerHideTimer.current)
    }

    useEffect(()=>{
        if(!musicPlayerRef.current) return
        if(position.pathname === '/music'){
            musicPlayerRef.current.style.top = 'auto'
            musicPlayerRef.current.style.bottom = '0'
            const lockDOM = document.querySelector('.portal_music_lock') as HTMLDivElement
            lockDOM.style.display = 'none'
        }else{
            const lockDOM = document.querySelector('.portal_music_lock') as HTMLDivElement
            lockDOM.style.display = 'flex'
            const rect = musicPlayerRef.current.getBoundingClientRect()
            musicPlayerRef.current.style.top = `-${rect.height}px`
            musicPlayerRef.current.style.bottom = 'auto'
        }
    },[position])
    return (
        <div className="portal">
            <Outlet></Outlet>
            <div 
                className='portal_musicPlayer' 
                ref={musicPlayerRef} 
                onMouseLeave={hideMusicPlayer}
                onMouseMove={stopHidePlayer}
            >
                <MusicPlayer></MusicPlayer>
                <div className='portal_music_lock'>
                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="1em" height="1em" filter="none" onClick={showMusicPlayer}>
                        <g>
                        <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 14.5c-2.49 0-4.5-2.01-4.5-4.5S9.51 7.5 12 7.5s4.5 2.01 4.5 4.5-2.01 4.5-4.5 4.5zm0-5.5c-.55 0-1 .45-1 1s.45 1 1 1 1-.45 1-1-.45-1-1-1z" fill="currentColor"></path>
                        </g>
                    </svg>
                </div>
            </div>
        </div>
    )
}

export default Portal